<template>
  <view class="body">
    <view class="tabs">
      <view class="tab">
        <text :class="tab == 'base' ? 'active' : ''" @tap="tabChange('base')"> 基本信息 </text>
        <view v-if="tab == 'base'" class="tab_active" />
      </view>
      <view class="tab">
        <text :class="tab == 'medical' ? 'active' : ''" @tap="tabChange('medical')">
          医疗信息
        </text>
        <view v-if="tab == 'medical'" class="tab_active" />
      </view>
    </view>
    <view class="info_content">
      <view v-if="tab == 'base'" class="info">
        <view class="cell">
          <view class="title">姓名</view>
          <view class="content content-disable">
            {{ baseInfo.patName }}
          </view>
        </view>
        <view class="cell">
          <view class="title">证件号</view>
          <view class="content content-disable"> {{ baseInfo.idNo }} </view>
        </view>
        <view class="cell">
          <view class="title">性别</view>
          <view class="content content-disable">
            {{ baseInfo.gender }}
          </view>
        </view>
        <view class="cell">
          <view class="title">年龄</view>
          <view class="content content-disable">
            {{ baseInfo.age }}
            <text style="display: inline-block; height: 100%"> 岁 </text>
          </view>
        </view>
        <!-- <view class="cell">
                        <view class="title">出生年月</view>
                        <view class="content">{{ baseInfo.birthday || '暂无' }}</view>
                    </view> -->
        <view class="cell">
          <view class="title">手机号</view>
          <view class="content content-disable">
            {{ baseInfo.phone }}
          </view>
        </view>
        <view class="cell">
          <view class="title">地址</view>
          <view class="content" @tap="showAdcdPop('省市区', 'area')">
            {{
              baseInfo.addressProvince
                ? `${baseInfo.addressProvince}-${baseInfo.addressCity}-${baseInfo.addressCountry}`
                : '请选择'
            }}

            <image
              class="form-arrow"
              src="@/static/image/form-arrow-right.png"
              mode="scaleToFill"
            />
          </view>
        </view>
        <view class="cell" style="flex-direction: column">
          <view class="title">详细地址</view>
          <view class="content" style="width: 100%; margin-top: 36rpx; text-align: left">
            <textarea
              style="width: 100%; height: 150rpx; text-align: left"
              type="text"
              v-model="baseInfo.address"
              placeholder="请输入"
              :border="false"
            />
          </view>
        </view>
        <view class="cell">
          <view class="title">ABO血型</view>
          <!-- <picker @change="rhChange" :value="rhIndex" :range="rhData"> -->
          <view class="content" @tap="showPop('ABO血型', 'CV04.50.005', 'abo')">
            <view class="form-select">
              {{ baseInfo.abo || '请选择' }}

              <image
                class="form-arrow"
                src="@/static/image/form-arrow-right.png"
                mode="scaleToFill"
              />
            </view>
          </view>
          <!-- </picker> -->
        </view>
        <view class="cell">
          <view class="title">Rh血型</view>
          <!-- <picker @change="rhChange" :value="rhIndex" :range="rhData"> -->
          <view class="content" @tap="showPop('Rh血型', 'CV04.50.020', 'rh')">
            <view class="form-select"
              >{{ baseInfo.rh || '请选择' }}

              <image
                class="form-arrow"
                src="@/static/image/form-arrow-right.png"
                mode="scaleToFill"
              />
            </view>
          </view>
          <!-- </picker> -->
        </view>
        <view class="cell">
          <view class="title">医疗支付方式</view>
          <view class="content" @tap="showPop('医疗支付方式', 'CV07.10.005', 'medicare')">
            <view class="form-select"
              >{{ baseInfo.medicare || '请选择' }}

              <image
                class="form-arrow"
                src="@/static/image/form-arrow-right.png"
                mode="scaleToFill"
              />
            </view>
          </view>
        </view>
        <view class="cell">
          <view class="title">婚姻状况</view>
          <view class="content" @tap="showPop('婚姻状况', 'GB/T_2261.2-2003', 'marital')">
            <view class="form-select"
              >{{ baseInfo.marital || '请选择' }}

              <image
                class="form-arrow"
                src="@/static/image/form-arrow-right.png"
                mode="scaleToFill"
              />
            </view>
          </view>
        </view>
        <!-- <view class="cell">
              <view class="title">常住类型</view>
              <view class="content">暂无</view>
            </view> -->
        <view class="cell">
          <view class="title">民族</view>
          <view class="content" @tap="showPop('民族', 'GB_3304-1991', 'nation')">
            <!-- <picker @change="nationChage" :value="nationIndex" :range="nationData"> -->
            <view class="form-select"
              >{{ baseInfo.nation || '请选择' }}

              <image
                class="form-arrow"
                src="@/static/image/form-arrow-right.png"
                mode="scaleToFill"
              />
            </view>
            <!-- </picker> -->
          </view>
        </view>
        <view class="cell">
          <view class="title">文化程度</view>
          <view class="content" @tap="showPop('文化程度', 'GB/T_4658-1984', 'education')">
            <view class="form-select"
              >{{ baseInfo.education || '请选择' }}

              <image
                class="form-arrow"
                src="@/static/image/form-arrow-right.png"
                mode="scaleToFill"
              />
            </view>
          </view>
        </view>
        <view class="cell">
          <view class="title">职业类别</view>
          <view class="content" @tap="showPop('职业类别', 'GB/T_6565-2009', 'occupation')">
            <view class="form-select"
              >{{ baseInfo.occupation || '请选择' }}

              <image
                class="form-arrow"
                src="@/static/image/form-arrow-right.png"
                mode="scaleToFill"
              />
            </view>
          </view>
        </view>
        <view class="cell" style="border-bottom-width: 0">
          <view class="title">联系人信息</view>
        </view>
        <view class="cell">
          <view class="title">联系人关系</view>
          <view class="content" @tap="showPop('联系人关系', 'GB/T_4761-2008', 'contactRelation')">
            <view class="form-select"
              >{{ baseInfo.contactRelation || '请选择' }}

              <image
                class="form-arrow"
                src="@/static/image/form-arrow-right.png"
                mode="scaleToFill"
              />
            </view>
          </view>
        </view>
        <view class="cell">
          <view class="title">联系人姓名</view>
          <view class="content">
            <input
              class="form_input"
              type="text"
              v-model="baseInfo.contactName"
              placeholder="请输入"
              :border="false"
            />
          </view>
        </view>
        <view class="cell">
          <view class="title">联系人电话</view>
          <view class="content">
            <input
              class="form_input"
              type="tel"
              v-model="baseInfo.contactPhone"
              placeholder="请输入"
              :border="false"
            />
          </view>
        </view>
      </view>
      <up-picker
        :key="pickerKey"
        :title="`选择${labelName}`"
        v-model:show.sync="show"
        :columns="popDataList"
        :defaultIndex="computedPopIndex"
        :closeOnClickOverlay="true"
        confirmColor="#00d1b6"
        @close="handleClose"
        @cancel="handleClose"
        @confirm="confirm"
      />

      <!-- 行政区划 -->
      <up-picker
        ref="uPickerRef"
        :key="pickerKey"
        title="省市区选择"
        v-model:show.sync="showAdcd"
        :columns="adcdData"
        :defaultIndex="adcdIndex"
        :closeOnClickOverlay="true"
        confirmColor="#00d1b6"
        @close="handleAdcdClose"
        @cancel="handleAdcdClose"
        @confirm="confirmAdcd"
        @change="adcdChange"
      />

      <view class="body" v-if="tab == 'medical'">
        <view class="result">
          <view class="result_box">
            <view class="title">
              <view class="line" />
              <view class="text">疾病史</view>
            </view>
            <view class="result_content">
              <text
                class="result-item"
                v-for="(item, index) of elapseHisList"
                :key="index"
                @tap="delDataHandle(index, elapseHisList)"
              >
                {{ item }} <text class="icon-text">×</text>
              </text>
              <!-- {{ result.elapseHis || '-' }} -->
              <text class="result-item" @tap="diseaseAdd('ICD-10', 'elapseHis')"
                ><text class="icon-text">＋</text> 添加
              </text>
            </view>
          </view>
          <view class="result_box">
            <view class="title">
              <view class="line" />
              <view class="text">过敏史</view>
            </view>
            <view class="result_content">
              <text
                class="result-item"
                v-for="(item, index) of allergyHisList"
                :key="index"
                @tap="delDataHandle(index, allergyHisList)"
              >
                {{ item }} <text class="icon-text">×</text>
              </text>
              <text class="result-item" @tap="addText('过敏史', 'allergy')">
                <text class="icon-text">＋</text> 添加
              </text>
              <!-- {{ result.allergyHis || '-' }} -->
            </view>
          </view>
          <view class="result_box">
            <view class="title">
              <view class="line" />
              <view class="text">家族史</view>
            </view>
            <view class="result_content">
              <text
                class="result-item"
                v-for="(item, index) of familyHisList"
                :key="index"
                @tap="delDataHandle(index, familyHisList)"
              >
                {{ item }} <text class="icon-text">×</text>
              </text>
              <text class="result-item" @tap="diseaseAdd('ICD-10', 'familyHis')">
                <text class="icon-text">＋</text> 添加
              </text>
            </view>
          </view>
          <view class="result_box">
            <view class="title">
              <view class="line" />
              <view class="text">外伤史</view>
            </view>
            <view class="result_content">
              <text
                class="result-item"
                v-for="(item, index) of hurtHisList"
                :key="index"
                @tap="delDataHandle(index, hurtHisList)"
              >
                {{ item }} <text class="icon-text">×</text>
              </text>
              <text class="result-item" @tap="addText('外伤史', 'hurt')">
                <text class="icon-text">＋</text> 添加
              </text>
            </view>
          </view>

          <view class="result_box" v-if="baseInfo.gender == '女性' && baseInfo.age > 8">
            <view class="title">
              <view class="line" />
              <view class="text">月经史</view>
            </view>
            <view class="result_content" style="padding: 0">
              <view class="cell cell-list">
                <view class="title">请输入初次月经年龄</view>
                <view class="content">
                  <input
                    class="form_input"
                    type="number"
                    placeholder="请输入"
                    :maxlength="2"
                    v-model="first_period_age"
                  />
                </view>
              </view>
              <view class="cell cell-list">
                <view class="title">请输入月经周期</view>
                <view class="content">
                  <input
                    class="form_input"
                    type="number"
                    placeholder="请输入"
                    :maxlength="2"
                    v-model="period_circle"
                  />
                </view>
              </view>
              <view class="cell cell-list">
                <view class="title">请输入月经持续天数</view>
                <view class="content">
                  <input
                    class="form_input"
                    type="number"
                    placeholder="请输入"
                    :maxlength="2"
                    v-model="period_duration"
                  />
                </view>
              </view>
              <view v-if="baseInfo.age > 30">
                <view class="cell cell-list">
                  <view class="title">请选择是否绝经</view>
                  <view class="content">
                    <picker
                      :value="if_menopauseIndex"
                      :range="['是', '否']"
                      @change="pickerChange($event, '3')"
                    >
                      <view class="form-select">
                        {{ ['是', '否'][if_menopauseIndex] || '请选择' }}

                        <image
                          class="form-arrow"
                          src="@/static/image/form-arrow-right.png"
                          mode="scaleToFill"
                        />
                      </view>
                    </picker>
                  </view>
                </view>
                <view class="cell cell-list" v-if="if_menopauseIndex == 0">
                  <view class="title">请输入绝经年龄</view>
                  <view class="content">
                    <input
                      class="form_input"
                      type="number"
                      placeholder="请输入"
                      :maxlength="2"
                      v-model="menopause_age"
                    />
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view v-if="baseInfo.gender == '女性' && baseInfo.age > 20" class="result_box">
            <view class="title">
              <view class="line" />
              <view class="text">婚育史</view>
            </view>
            <view class="result_content" style="padding: 0">
              <view class="cell cell-list">
                <view class="title">请选择婚姻状态</view>
                <view class="content">
                  <picker
                    :value="marriage_statusIndex"
                    :range="['已婚', '未婚']"
                    @change="pickerChange($event, '1')"
                  >
                    <view class="form-select">
                      {{ ['已婚', '未婚'][marriage_statusIndex] || '请选择' }}

                      <image
                        class="form-arrow"
                        src="@/static/image/form-arrow-right.png"
                        mode="scaleToFill"
                      />
                    </view>
                  </picker>
                </view>
              </view>
              <view v-if="marriage_statusIndex == 0">
                <view class="cell cell-list">
                  <view class="title">请选择生育状态</view>
                  <view class="content">
                    <picker
                      :value="fertility_statusIndex"
                      :range="['已育', '未育']"
                      @change="pickerChange($event, '2')"
                    >
                      <view class="form-select">
                        {{ ['已育', '未育'][fertility_statusIndex] || '请选择' }}

                        <image
                          class="form-arrow"
                          src="@/static/image/form-arrow-right.png"
                          mode="scaleToFill"
                        />
                      </view>
                    </picker>
                  </view>
                </view>
                <view v-if="fertility_statusIndex == 0">
                  <view class="cell cell-list">
                    <view class="title">请输入妊娠次数</view>
                    <view class="content">
                      <input
                        class="form_input"
                        type="number"
                        placeholder="请输入"
                        :maxlength="2"
                        v-model="pregnancy_count"
                      />
                    </view>
                  </view>
                  <view class="cell cell-list">
                    <view class="title">请输入生育次数</view>
                    <view class="content">
                      <input
                        class="form_input"
                        type="number"
                        placeholder="请输入"
                        :maxlength="2"
                        v-model="birth_count"
                      />
                    </view>
                  </view>
                  <view class="cell cell-list">
                    <view class="title">请输入流产次数</view>
                    <view class="content">
                      <input
                        class="form_input"
                        type="number"
                        placeholder="请输入"
                        :maxlength="2"
                        v-model="miscarriage_count"
                      />
                    </view>
                  </view>
                  <view class="cell cell-list">
                    <view class="title">请输入死产次数</view>
                    <view class="content">
                      <input
                        class="form_input"
                        type="number"
                        placeholder="请输入"
                        :maxlength="2"
                        v-model="stillbirth_count"
                      />
                    </view>
                  </view>
                  <view class="cell cell-list">
                    <view class="title">请输入剖腹产次数</view>
                    <view class="content">
                      <input
                        class="form_input"
                        type="number"
                        placeholder="请输入"
                        :maxlength="2"
                        v-model="cesarean_section_count"
                      />
                    </view>
                  </view>
                  <view class="cell cell-list">
                    <view class="title">请输入顺产次数</view>
                    <view class="content">
                      <input
                        class="form_input"
                        type="number"
                        placeholder="请输入"
                        :maxlength="2"
                        v-model="vaginal_birth_count"
                      />
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <up-popup
            :show="showMedicalInfo"
            :round="16"
            mode="bottom"
            class="detail_pop"
            closeable
            @close="showMedicalInfo = false"
          >
            <view class="title">选择{{ labelName }}</view>
            <view class="query-list">
              <view
                :class="['query-item', item.dictLabel === popValue ? 'query-action' : '']"
                v-for="(item, index) in popDataList"
                :key="index"
                @tap="popFun(item)"
              >
                <text>{{ item.dictLabel }}</text>
              </view>
            </view>
            <view class="query-btn">
              <text @tap="popMedicalInfoSure" class="query-btn-text">确定</text>
            </view>
          </up-popup>

          <up-popup
            :show="showDiseaseInfo"
            :round="16"
            mode="bottom"
            class="detail_pop"
            closeable
            @close="showDiseaseInfo = false"
          >
            <view class="title">选择{{ addDiseaseTypeLabel }}</view>
            <view class="query_search">
              <input
                class="query_input"
                type="text"
                v-model="searchQuery"
                :placeholder="`搜索并选择疾病`"
                @input="filterEthnicities"
              />
            </view>
            <view class="query-list">
              <checkbox-group>
                <label
                  class="uni-list-cell uni-list-cell-pd"
                  v-for="item in diseaseList"
                  :key="item.dictValue"
                >
                  <view>{{ item.dictLabel }}</view>
                  <view>
                    <radio
                      color="#00D1B6"
                      :value="item.dictLabel"
                      :checked="item.checked"
                      @tap="checkboxChange(item)"
                    />
                    <!-- <checkbox
                      class="checkbox-input"
                      :value="item.dictLabel"
                      :checked="item.checked"
                    /> -->
                  </view>
                </label>
              </checkbox-group>
            </view>
            <view class="query-btn">
              <text @tap="popDiseaseSure" class="query-btn-text">确定</text>
            </view>
          </up-popup>

          <up-popup
            :show="showText"
            :closeable="true"
            :round="16"
            mode="center"
            @close="showText = false"
          >
            <view class="popup-wrap">
              <view class="title-textarea">{{ textLabel }}</view>
              <view class="textInput">
                <textarea
                  :key="popupKey"
                  style="height: 200rpx"
                  class="textarea"
                  v-model="textValue"
                  placeholder-class="placeholder-textarea"
                  :placeholder="`请输入${textLabel}`"
                  :maxlength="20"
                />
                <view class="text-count">{{ inputLength }}/20</view>
              </view>
              <view class="authenticationBtn">
                <view class="wrapsTwo">
                  <view class="cancel" @tap="cancelText">取消</view>
                  <view class="goAuthentication" @tap="sureText">确定</view>
                </view>
              </view>
            </view>
          </up-popup>
        </view>
      </view>
    </view>
    <view class="msg-btn-box">
      <text class="msg-btn" @tap="msgSave">保存</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import { base_info, history } from '@/api/moreMessage'
import { onLoad, onShow } from '@dcloudio/uni-app'
import {
  getDictAreaList,
  getDictList,
  getMedicalInfo,
  saveMedicalInfo,
  updatePatientInfo
} from './moreMessage.api'

const tab = ref('base')
const show = ref(false)
const popType = ref('')
const baseInfo = ref<any>({})
// const medicalInfo = ref({})

const showMedicalInfo = ref(false)
const showDiseaseInfo = ref(false)
const diseaseList = ref([])

const type = ref('')
const empi = ref('')

const labelName = ref<string>('')
const searchQuery = ref<string>('')
const popValue = ref<string>('')
const popCode = ref<string>('')
const diseaseCode = ref<string>('')
const diseaseType = ref<string>('')
const elapseHisList = ref<any>([])
const allergyHisList = ref<any>([])
const familyHisList = ref<any>([])
const hurtHisList = ref<any>([])

const first_period_age = ref()
const period_circle = ref()
const period_duration = ref()
const if_menopause = ref('')
const if_menopauseIndex = ref()
const menopause_age = ref()

const marriage_status = ref('')
const marriage_statusIndex = ref()
const fertility_status = ref('')
const fertility_statusIndex = ref()
const pregnancy_count = ref()
const birth_count = ref()
const miscarriage_count = ref()
const stillbirth_count = ref()
const cesarean_section_count = ref()
const vaginal_birth_count = ref()

const uPickerRef = ref()

onLoad((option) => {
  type.value = option.empi ? 'body' : ''
  empi.value = option.empi ? option.empi : ''
})

onShow(() => {
  init()
})

const textValue = ref<string>('')
const showText = ref(false)
const inputLength = computed(() => {
  // 已输入的字数
  return textValue.value ? (textValue.value.length > 20 ? 20 : textValue.value.length) : 0
})

const tabChange = (item: string) => {
  tab.value = item
  if (tab.value == 'medical') {
    getHistory()
  }
}

const popDataList = ref<any>([[]])
let originDataLIst = reactive([])
const popKey = ref<any>('')
const popIndex = ref<number[]>([0])
const pickerKey = ref(0) // 用于强制刷新 picker

const showPop = async (val, typeCode: string, key: string) => {
  popIndex.value = [0]
  popDataList.value = []
  popKey.value = key
  // searchQuery.value = ''
  labelName.value = val
  popType.value = val
  popValue.value = baseInfo.value[key]
  popCode.value = baseInfo.value[`${key}Code`]

  await getDictList({ type: typeCode, label: '' }).then((res: any) => {
    originDataLIst = res.data.list

    const data = res.data.list.map((vo) => {
      return vo.dictLabel
    })

    popDataList.value.push(data)

    const index = popDataList.value[0].findIndex((item: any) => popValue.value === item)

    if (index > -1) {
      popIndex.value = [index]
    }
  })
  pickerKey.value += 1
  await nextTick()
  show.value = true
}

const confirm = (e) => {
  popValue.value = e.value[0]
  show.value = false

  const data: any = originDataLIst.filter((vo) => vo.dictLabel === popValue.value)

  baseInfo.value[`${popKey.value}Code`] = data[0].dictValue
  baseInfo.value[popKey.value] = data[0].dictLabel
}

const handleClose = () => {
  show.value = false
}

const computedPopIndex = computed(() => popIndex.value)

// 行政区划

const adcdData = ref([])
const adcdIndex = ref<any>([])
const showAdcd = ref(false)

const provinceList = ref([])
const cityList = ref([])
const countyList = ref([])

const showAdcdPop = async (val, typeCode: string) => {
  adcdIndex.value = [0, 0, 0]
  adcdData.value = []
  labelName.value = val

  const { data: provinceData } = await getDictAreaList({ type: typeCode, label: '', parentId: '0' })
  provinceList.value = provinceData.list
  if (baseInfo.value.addressProvinceCode) {
    const indexProvince = provinceData.list.findIndex(
      (vo) => vo.dictValue == baseInfo.value.addressProvinceCode
    )

    if (indexProvince > -1) {
      adcdIndex.value[0] = indexProvince
    }
  } else {
    adcdIndex.value[0] = 0
  }
  const provinceValue = provinceData.list.map((vo) => {
    return vo.dictLabel
  })
  adcdData.value.push(provinceValue)

  const { data: cityData } = await getDictAreaList({
    type: typeCode,
    label: '',
    parentId: provinceData.list[adcdIndex.value[0]].dictValue
  })
  cityList.value = cityData.list
  if (baseInfo.value.addressCityCode) {
    const indexCity = cityData.list.findIndex(
      (vo) => vo.dictValue == baseInfo.value.addressCityCode
    )
    if (indexCity > -1) {
      adcdIndex.value[1] = indexCity
    }
  } else {
    adcdIndex.value[1] = 0
  }

  const cityValue = cityData.list.map((vo) => {
    return vo.dictLabel
  })
  adcdData.value.push(cityValue)

  const { data: countyData } = await getDictAreaList({
    type: typeCode,
    label: '',
    parentId: cityData.list[adcdIndex.value[1]].dictValue
  })
  countyList.value = countyData.list
  if (baseInfo.value.addressCountryCode) {
    const indexCounty = countyData.list.findIndex(
      (vo) => vo.dictValue == baseInfo.value.addressCountryCode
    )

    if (indexCounty > -1) {
      adcdIndex.value[2] = indexCounty
    }
  } else {
    adcdIndex.value[2] = 0
  }
  const countyValue = countyData.list.map((vo) => {
    return vo.dictLabel
  })
  adcdData.value.push(countyValue)

  pickerKey.value += 1
  await nextTick()
  showAdcd.value = true
}

const handleAdcdClose = () => {
  showAdcd.value = false
}
const confirmAdcd = (e) => {
  baseInfo.value.addressCity = e.value[1]
  baseInfo.value.addressCityCode = cityList.value[e.indexs[1]].dictValue
  baseInfo.value.addressCountry = e.value[2]
  baseInfo.value.addressCountryCode = countyList.value[e.indexs[2]].dictValue
  baseInfo.value.addressProvince = e.value[0]
  baseInfo.value.addressProvinceCode = provinceList.value[e.indexs[0]].dictValue

  showAdcd.value = false
}

const adcdChange = async (e) => {
  //   provinceList
  // cityList
  // countyList
  if (e.columnIndex == 0) {
    adcdIndex.value = [e.indexs[0], 0, 0]
    // 市级
    const { data: cityData } = await getDictAreaList({
      label: '',
      parentId: provinceList.value[adcdIndex.value[0]].dictValue
    })
    cityList.value = cityData.list
    const cityValue = cityList.value.map((vo) => {
      return vo.dictLabel
    })

    adcdIndex.value[1] = 0
    uPickerRef.value.setColumnValues(1, cityValue)

    // 区级
    const { data: countyData } = await getDictAreaList({
      label: '',
      parentId: cityList.value[0].dictValue
    })
    countyList.value = countyData.list
    const countyValue = countyList.value.map((vo) => {
      return vo.dictLabel
    })

    adcdIndex.value[2] = 0
    uPickerRef.value.setColumnValues(2, countyValue)
  }

  if (e.columnIndex == 1) {
    adcdIndex.value = e.indexs
    // 区级
    const { data: countyData } = await getDictAreaList({
      label: '',
      parentId: cityList.value[adcdIndex.value[1]].dictValue
    })
    countyList.value = countyData.list
    const countyValue = countyList.value.map((vo) => {
      return vo.dictLabel
    })

    adcdIndex.value[2] = 0
    uPickerRef.value.setColumnValues(2, countyValue)
  }
}
const init = () => {
  base_info({ userId: JSON.parse(uni.getStorageSync('userInfo')).userId, empi: empi.value }).then(
    (res) => {
      baseInfo.value = res.data
    }
  )
  if (baseInfo.value.contactName) {
    baseInfo.value.contacts =
      baseInfo.value.contactName +
      ' ' +
      baseInfo.value.contactRelation +
      ' ' +
      baseInfo.value.contactPhone
  }
}
const getHistory = () => {
  familyHisList.value = []
  elapseHisList.value = []
  allergyHisList.value = []
  hurtHisList.value = []
  getMedicalInfo({ empi: baseInfo.value.empi }).then((res) => {
    res.data.forEach((vo) => {
      if (vo.extKey == 'family') {
        familyHisList.value = [...vo.extValue.split('#')]
      }
      if (vo.extKey == 'disease') {
        elapseHisList.value = [...vo.extValue.split('#')]
      }

      if (vo.extKey == 'allergy') {
        allergyHisList.value = [...vo.extValue.split('#')]
      }

      if (vo.extKey == 'trauma') {
        hurtHisList.value = [...vo.extValue.split('#')]
      }

      if (vo.extKey == 'first_period_age') {
        first_period_age.value = vo.extValue
      }

      if (vo.extKey == 'period_circle') {
        period_circle.value = vo.extValue
      }

      if (vo.extKey == 'period_duration') {
        period_duration.value = vo.extValue
      }

      if (vo.extKey == 'if_menopause') {
        if_menopause.value = vo.extValue
        if (if_menopause.value == '是') {
          if_menopauseIndex.value = 0
        } else {
          if_menopauseIndex.value = 1
        }
      }

      if (vo.extKey == 'menopause_age') {
        menopause_age.value = vo.extValue
      }

      if (vo.extKey == 'marriage_status') {
        marriage_status.value = vo.extValue
        if (marriage_status.value == '已婚') {
          marriage_statusIndex.value = 0
        } else {
          marriage_statusIndex.value = 1
        }
      }

      if (vo.extKey == 'fertility_status') {
        fertility_status.value = vo.extValue
        if (fertility_status.value === '已育') {
          fertility_statusIndex.value = 0
        } else {
          fertility_statusIndex.value = 1
        }
      }

      if (vo.extKey == 'pregnancy_count') {
        pregnancy_count.value = vo.extValue
      }
      if (vo.extKey == 'birth_count') {
        birth_count.value = vo.extValue
      }
      if (vo.extKey == 'miscarriage_count') {
        miscarriage_count.value = vo.extValue
      }
      if (vo.extKey == 'stillbirth_count') {
        stillbirth_count.value = vo.extValue
      }
      if (vo.extKey == 'cesarean_section_count') {
        cesarean_section_count.value = vo.extValue
      }
      if (vo.extKey == 'vaginal_birth_count') {
        vaginal_birth_count.value = vo.extValue
      }
    })
  })
}

const pickerChange = (e, index) => {
  const value = e.detail.value
  if (index == 1) {
    marriage_statusIndex.value = parseFloat(value)
    if (value == 1) {
      fertility_statusIndex.value = -1
      pregnancy_count.value = undefined
      birth_count.value = undefined
      miscarriage_count.value = undefined
      stillbirth_count.value = undefined
      cesarean_section_count.value = undefined
      vaginal_birth_count.value = undefined
    }
  } else if (index == 2) {
    fertility_statusIndex.value = parseFloat(value)
    if (value == 1) {
      pregnancy_count.value = undefined
      birth_count.value = undefined
      miscarriage_count.value = undefined
      stillbirth_count.value = undefined
      cesarean_section_count.value = undefined
      vaginal_birth_count.value = undefined
    }
  } else if (index == 3) {
    if_menopauseIndex.value = parseFloat(value)

    if (value == 1) {
      menopause_age.value = undefined
    }
  }
}

// 删除
const delDataHandle = (index: number, data: any) => {
  data.splice(index, 1)
}

// 保存
const msgSave = () => {
  if (tab.value == 'base') {
    uni.showLoading()
    const baseData = JSON.parse(JSON.stringify(baseInfo.value))
    delete baseData.patName
    delete baseData.idNo
    delete baseData.phone
    const phoneReg = /^1[3456789]\d{9}$/
    if (baseData.contactPhone) {
      if (!phoneReg.test(baseData.contactPhone)) {
        uni.showToast({
          title: '请输入正确的联系人电话',
          icon: 'none'
        })
        return
      }
    }

    updatePatientInfo(baseData).then(() => {
      uni.hideLoading()
      uni.showToast({
        title: '保存成功'
      })

      setTimeout(() => {
        uni.navigateBack()
      }, 300)
    })
  } else {
    const data = []
    const family = familyHisList.value.join('#')
    const elapse = elapseHisList.value.join('#')
    const allergy = allergyHisList.value.join('#')
    const hurt = hurtHisList.value.join('#')

    if (family) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'family',
        extValue: family
      })
    }
    if (elapse) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'disease',
        extValue: elapse
      })
    }
    if (allergy) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'allergy',
        extValue: allergy
      })
    }
    if (hurt) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'trauma',
        extValue: hurt
      })
    }

    if (first_period_age.value && Number(first_period_age.value) >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'first_period_age',
        extValue: first_period_age.value
      })
    }
    if (period_circle.value && Number(period_circle.value) >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'period_circle',
        extValue: period_circle.value
      })
    }
    if (period_duration.value && Number(period_duration.value) >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'period_duration',
        extValue: period_duration.value
      })
    }
    if (if_menopauseIndex.value >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'if_menopause',
        extValue: ['是', '否'][if_menopauseIndex.value]
      })
    }
    if (menopause_age.value && Number(menopause_age.value) >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'menopause_age',
        extValue: menopause_age.value
      })
    }
    if (marriage_statusIndex.value >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'marriage_status',
        extValue: ['已婚', '未婚'][marriage_statusIndex.value]
      })
    }
    if (fertility_statusIndex.value >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'fertility_status',
        extValue: ['已育', '未育'][fertility_statusIndex.value]
      })
    }
    if (pregnancy_count.value && Number(pregnancy_count.value) >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'pregnancy_count',
        extValue: pregnancy_count.value
      })
    }

    if (Number(pregnancy_count.value) > 20) {
      uni.showToast({
        title: '妊娠次数不能超过20次',
        icon: 'none'
      })

      return
    }

    if (birth_count.value && Number(birth_count.value) >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'birth_count',
        extValue: birth_count.value
      })
    }
    if (Number(birth_count.value) > 20) {
      uni.showToast({
        title: '生育次数不能超过20次',
        icon: 'none'
      })

      return
    }
    if (miscarriage_count.value && Number(miscarriage_count.value) >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'miscarriage_count',
        extValue: miscarriage_count.value
      })
    }
    if (Number(miscarriage_count.value) > 20) {
      uni.showToast({
        title: '流产次数不能超过20次',
        icon: 'none'
      })

      return
    }
    if (stillbirth_count.value && Number(stillbirth_count.value) >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'stillbirth_count',
        extValue: stillbirth_count.value
      })
    }

    if (Number(stillbirth_count.value) > 20) {
      uni.showToast({
        title: '死产次数不能超过20次',
        icon: 'none'
      })

      return
    }
    if (cesarean_section_count.value && Number(cesarean_section_count.value) >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'cesarean_section_count',
        extValue: cesarean_section_count.value
      })
    }

    if (Number(cesarean_section_count.value) > 20) {
      uni.showToast({
        title: '剖腹产次数不能超过20次',
        icon: 'none'
      })

      return
    }

    if (vaginal_birth_count.value && Number(vaginal_birth_count.value) >= 0) {
      data.push({
        empi: baseInfo.value.empi,
        extKey: 'vaginal_birth_count',
        extValue: vaginal_birth_count.value
      })
    }

    if (Number(vaginal_birth_count.value) > 20) {
      uni.showToast({
        title: '顺产次数不能超过20次',
        icon: 'none'
      })

      return
    }

    // 测试提出医疗信息没填也可以保存
    if (data.length == 0) {
      data[0] = {
        empi: baseInfo.value.empi,
        extKey: '',
        extValue: ''
      }
    }
    saveMedicalInfo(data).then((res) => {
      uni.hideLoading()
      uni.showToast({
        title: '保存成功'
      })

      setTimeout(() => {
        uni.navigateBack()
      }, 300)
    })
    return
  }
}

// 疾病
const filterEthnicities = (e) => {
  searchQuery.value = e.detail.value
  getDataList(diseaseCode.value, searchQuery.value)
}

const addDiseaseTypeLabel = ref<string>('')
const diseaseAdd = (code: string, type: string) => {
  if (type == 'elapseHis') {
    addDiseaseTypeLabel.value = '疾病史'
    checkDiseaseData.value = JSON.parse(JSON.stringify(elapseHisList.value))
  } else {
    addDiseaseTypeLabel.value = '家庭史'
    checkDiseaseData.value = JSON.parse(JSON.stringify(familyHisList.value))
  }
  diseaseType.value = type
  diseaseCode.value = code
  showDiseaseInfo.value = true
  searchQuery.value = ''
  getDataList(code, searchQuery.value)
}

const getDataList = (code, filter) => {
  diseaseList.value = []
  getDictList({ type: code, label: filter }).then((res) => {
    diseaseList.value = res.data.list.map((vo) => {
      if (diseaseType.value == 'elapseHis') {
        if (elapseHisList.value.includes(vo.dictLabel)) {
          vo.checked = true
        } else {
          vo.checked = false
        }
      } else {
        if (familyHisList.value.includes(vo.dictLabel)) {
          vo.checked = true
        } else {
          vo.checked = false
        }
      }
      return { ...vo }
    })
    console.log(checkDiseaseData.value)
  })
}

const popFun = (data: any) => {
  popValue.value = data.dictLabel
  popCode.value = data.dictValue
  // show.value = false
}

const popMedicalInfoSure = () => {}
const textLabel = ref<string>('')
const textType = ref<string>('')
const popupKey = ref<number>(0)
// 过敏史、外伤史输入
const addText = (name: string, type: string) => {
  textLabel.value = name
  textType.value = type
  textValue.value = ''
  showText.value = true

  // uni.showModal({
  //   title: '过敏史',
  //   content: '',
  //   editable: true,
  //   cancelColor: '#666',
  //   confirmColor: '#00d1b6',
  //   placeholderText: '请输入过敏史',
  //   success: (res: any) => {
  //     if (res.confirm) {
  //       allergyHisList.value.push(res.content)
  //       allergyHisList.value = [...new Set(allergyHisList.value)]
  //     }
  //   }
  // })
}

const sureText = () => {
  console.log(textValue.value)
  // console.log(textType.value)
  if (textValue.value) {
    const value = textValue.value.replace(/\s+/g, '').substring(0, 20)
    if (textType.value == 'allergy') {
      allergyHisList.value.push(value)
      allergyHisList.value = [...new Set(allergyHisList.value)]
    } else {
      hurtHisList.value.push(value)
      hurtHisList.value = [...new Set(hurtHisList.value)]
    }

    showText.value = false
    popupKey.value += 1

    textValue.value = ''
    nextTick(() => {
      textValue.value = ''
    })
  } else {
    uni.showToast({
      title: '请输入内容',
      icon: 'none'
    })
  }
}

const cancelText = () => {
  showText.value = false
  popupKey.value += 1

  textValue.value = ''
  nextTick(() => {
    textValue.value = ''
  })
}

const checkDiseaseData = ref([])
const checkboxChange = (data: any) => {
  data.checked = !data.checked
  if (data.checked) {
    checkDiseaseData.value.push(data.dictLabel)
  } else {
    checkDiseaseData.value = checkDiseaseData.value.filter((item) => item !== data.dictLabel)
  }
  console.log(checkDiseaseData.value)
}
const popDiseaseSure = () => {
  console.log(checkDiseaseData.value)
  if (diseaseType.value == 'elapseHis') {
    elapseHisList.value = [...new Set([...elapseHisList.value, ...checkDiseaseData.value])]
  } else {
    familyHisList.value = [...new Set([...familyHisList.value, ...checkDiseaseData.value])]
  }
  showDiseaseInfo.value = false
}
</script>

<style lang="scss" scoped>
.body {
  position: relative;

  .tabs {
    width: 100%;
    height: 100rpx;
    background: #fff;

    .tab {
      display: inline-block;
      height: 100rpx;
      padding: 0 32rpx;
      font-size: 28rpx;
      font-weight: 400;
      color: #666;

      text {
        display: block;
        height: 95rpx;
        line-height: 95rpx;
      }

      .active {
        font-size: 36rpx;
        font-weight: 700;
        color: #222;
      }

      .tab_active {
        width: 24rpx;
        height: 6rpx;
        margin: 0 auto;
        background: #00d1b6;
        border-radius: 4rpx;
      }
    }
  }

  .info_content {
    height: calc(100vh - 305rpx);
    padding: 24rpx 32rpx 0;
    overflow: auto;

    .info {
      padding: 0 32rpx;
      background: #fff;
      border-radius: 12rpx;

      .cell {
        display: flex;
        justify-content: space-between;
        padding: 34rpx 0;
        border-bottom: 1rpx solid #e5e6eb;

        .title {
          font-size: 30rpx;
          font-weight: 700;
          color: #333;
        }

        .content {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: flex-end;
          width: 400rpx;
          font-size: 30rpx;
          font-weight: 400;
          color: #222;

          .more {
            width: 40rpx;
            height: 40rpx;
            transform: translateY(10rpx);
          }
        }
      }

      .cell:last-child {
        border: none;
      }
    }

    .u-popup {
      .title {
        height: 108rpx;
        font-size: 32rpx;
        font-weight: 700;
        line-height: 108rpx;
        color: #222;
        text-align: center;
      }

      .lists {
        box-sizing: border-box;
        width: 640rpx;
        max-height: 500rpx;
        padding: 0 40rpx;
        margin-bottom: 40rpx;
        overflow: auto;

        .address_item {
          margin-bottom: 40rpx;
          font-size: 30rpx;
          font-weight: 400;
          color: #666;

          .item_top {
            margin-bottom: 20rpx;
          }
        }

        .contact_item {
          display: flex;
          justify-content: flex-start;
          padding-left: 58rpx;
          margin-bottom: 40rpx;
          font-size: 30rpx;
          font-weight: 400;
          color: #666;

          .name {
            width: 20%;
          }

          .relation {
            width: 20%;
            margin-left: 40rpx;
          }

          .phone {
            width: 50%;
            margin-left: 40rpx;
          }
        }

        .contact_item:last-child {
          margin-bottom: 0 !important;
        }
      }
    }
  }
}

.form_input {
  display: inline-block;
  text-align: right;
}

.form-select {
  display: flex;
  align-items: center;
}

.form-arrow {
  width: 40rpx;
  height: 40rpx;
}

.query-list {
  height: 600rpx;
  padding: 0 32rpx;
  overflow-y: scroll;

  .query-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    height: 108rpx;
    border-bottom: 1rpx solid #e5e6eb;
  }

  .query-action {
    color: #00d1b6;
    border: 1rpx solid #00d1b6;
  }
}

::v-deep .u-icon__icon {
  top: 16rpx !important;
  font-size: 40rpx !important;
}

::v-deep .u-safe-area-inset-bottom {
  padding-bottom: 0 !important;
}

.query_search {
  width: 100%;
  height: 120rpx;
  padding: 24rpx 32rpx;

  .query_input {
    height: 72rpx;
    padding-left: 24rpx;
    font-size: 32rpx;
    background: #fafafa;
    border-radius: 40rpx;
  }
}

.query-btn {
  width: 100%;
  height: 136rpx;
  padding: 24rpx 32rpx;
  margin-bottom: 68rpx;

  .query-btn-text {
    display: inline-block;
    width: 100%;
    height: 88rpx;
    font-size: 32rpx;
    font-weight: 700;
    line-height: 88rpx;
    color: #fff;
    text-align: center;
    background: #00d1b6;
    border: 2rpx solid #00d1b6;
    border-radius: 44rpx;
  }
}

.msg-btn-box {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 204rpx;
  padding: 24rpx 32rpx;
  background-color: #fff;

  .msg-btn {
    display: inline-block;
    width: 100%;
    height: 88rpx;
    font-size: 32rpx;
    font-weight: 700;
    line-height: 88rpx;
    color: #fff;
    text-align: center;
    background: #00d1b6;
    border-radius: 44rpx;
  }
}

.result {
  height: calc(100vh - 320rpx);
  padding: 24rpx 32rpx;
  overflow-y: scroll;
  background: #fff;
  border-radius: 12rpx;

  .result_box {
    // padding-bottom: 40rpx;
    margin-bottom: 32rpx;
    border-bottom: 1rpx solid #e5e6eb;

    .title {
      margin-bottom: 16rpx;

      .line {
        display: inline-block;
        width: 8rpx;
        height: 28rpx;
        background: #00d1b6;
      }

      .text {
        display: inline-block;
        margin-left: 24rpx;
        font-size: 32rpx;
        font-weight: 700;
        color: #222;
      }
    }

    .result_content {
      padding: 8rpx 24rpx 0rpx;
      font-size: 30rpx;
      // font-weight: 400;
      line-height: 54rpx;
      text-align: justify;
      // background: #fafafa;
      border-radius: 12rpx;

      .cell {
        display: flex;
        justify-content: space-between;
        padding: 34rpx 0;
        border-bottom: 1rpx solid #e5e6eb;

        .title {
          font-size: 30rpx;
          font-weight: 700;
          color: #333;
        }

        .content {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: flex-end;
          width: 200rpx;
          font-size: 30rpx;
          font-weight: 400;
          color: #222;

          .more {
            width: 40rpx;
            height: 40rpx;
            transform: translateY(10rpx);
          }
        }
      }

      .cell:last-child {
        border: none;
      }
    }
  }

  .result_box:last-child {
    padding-bottom: 0;
    margin-bottom: 0;
    border: none;
  }
}

.result-item {
  display: inline-block;
  padding: 4rpx 18rpx 6rpx;
  margin-right: 32rpx;
  margin-bottom: 24rpx;
  font-size: 24rpx;
  line-height: 40rpx;
  color: #165dff;
  background: #e8f3ff;
  border-radius: 4rpx;
}

.uni-list-cell-pd {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 108rpx;
  border-bottom: 1rpx solid #e5e6eb;
}

.content-disable {
  color: #999 !important;
}

::v-deep .u-popup {
  .popup-wrap {
    width: 80vw;

    .title-textarea {
      padding: 32rpx;
      font-size: 34rpx;
      font-weight: 700;
      color: #222;
      text-align: center;
    }

    .textInput {
      position: relative;

      .textarea {
        box-sizing: border-box;
        display: block;
        width: calc(100% - 60rpx);
        height: 260rpx;
        padding: 20rpx;
        margin: 0 auto;
        background: #fafafa;
        // border: 1px solid #e0e0e0;
        border-radius: 8rpx;
      }

      .text-count {
        box-sizing: border-box;
        display: block;
        width: calc(100% - 60rpx);
        padding: 10rpx 0 0rpx;
        margin: 0 auto;
        color: #666;
        text-align: right;
      }
    }

    .authenticationBtn {
      background: #fff;
      border-bottom-right-radius: 16rpx;
      border-bottom-left-radius: 16rpx;

      .wrapsTwo {
        margin-top: 24rpx;
        font-size: 32rpx;
        color: #666;
        text-align: center;
        border-top: 1rpx solid #e5e6eb;

        .cancel {
          display: inline-block;
          width: calc(50% - 1rpx);
          height: 88rpx;
          line-height: 88rpx;
          vertical-align: middle;
          border-right: 1rpx solid #e5e6eb;
        }

        .goAuthentication {
          display: inline-block;
          width: 50%;
          height: 88rpx;
          line-height: 88rpx;
          color: #00d1b6;
          vertical-align: middle;
        }
      }
    }
  }
}

::v-deep.placeholder-textarea {
  font-size: 28rpx;
  color: #999 !important;
}

.icon-text {
  display: inline-block;
  font-size: 34rpx;
  transform: translateY(2rpx);
}

.cell-list {
  padding: 34rpx 0 24rpx;
}

.checkbox-input {
  position: relative;
  width: 20rpx;
  height: 20rpx;
  margin-right: 10rpx;

  /* 隐藏默认复选框样式 */
  appearance: none;
  background-color: #fff;
  border: 1rpx solid #dcdcdc;
  border-radius: 4rpx;
}

.checkbox-input:checked {
  /* 选中时自定义样式 */
  background-color: #007aff;
  border-color: #007aff;
}
</style>
<style>
.u-popup__content {
  border-radius: 32rpx 32rpx 0 0;
}
</style>
